package com.app.twth.ui.printer;


import android.app.Activity;
import android.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.app.twth.R;
import com.app.twth.app.Constant;
import com.app.twth.utils.PreferencesUtil;


/**
 * Created by Administrator
 *
 * @author 猿史森林
 * Date: 2017/11/30
 * Class description:
 */
public class WifiParameterConfigDialog {
    private Activity mContext;
    private WifiConfigCallback wifiConfigCallback;

    public interface WifiConfigCallback {
        void callback(String ip, int port);
    }


    public WifiParameterConfigDialog(Activity context, WifiConfigCallback callback) {
        mContext = context;
        this.wifiConfigCallback = callback;
    }

    public void show() {
        View contentView = View.inflate(mContext, R.layout.dialog_wifi_config, null);
        final EditText etWifiIpConfig = (EditText) contentView.findViewById(R.id.et_wifi_ip);
        final EditText etWifiPortConfig = (EditText) contentView.findViewById(R.id.et_wifi_port);
        final String ip = PreferencesUtil.getString(mContext, Constant.WIFI_CONFIG_IP, Constant.WIFI_DEFAULT_IP);
        final String port = String.valueOf(PreferencesUtil.getInt(mContext, Constant.WIFI_CONFIG_PORT, Constant.WIFI_DEFAULT_PORT));
        etWifiIpConfig.setText(ip);
        etWifiPortConfig.setText(port);
        AlertDialog alertDialog = new AlertDialog.Builder(mContext).setView(contentView)
                .setNegativeButton(mContext.getString(R.string.str_confirm), (dialog, which) -> {
                    final String strIp = etWifiIpConfig.getText().toString().trim();
                    final String strPort = etWifiPortConfig.getText().toString().trim();
                    System.out.println("strIp --> " + strIp + "\tstrPort --> " + strPort);
                    if (!TextUtils.isEmpty(strIp) && !TextUtils.isEmpty(strPort)) {
                        if (!strIp.equals(ip)) {
                            PreferencesUtil.putString(mContext, strIp, Constant.WIFI_CONFIG_IP);
                        }
                        if (!strPort.equals(port)) {
                            PreferencesUtil.putInt(mContext, Constant.WIFI_CONFIG_PORT, Integer.parseInt(strPort));
                        }
                        wifiConfigCallback.callback(strIp, Integer.parseInt(strPort));
                    }
                })
                .setPositiveButton(mContext.getString(R.string.str_cancel), (dialog, which) -> {

                }).show();
        alertDialog.setCanceledOnTouchOutside(false);
    }
}
